#include "config.h"

#include "ms2lstat.h"

#define	BUFMAX	8192

ECMBOOL	stop_on_error;
ECMBOOL	suppress_display_error;

ecm_uint64	n_logs;
ecm_uint64	n_error_logs;

lent_t *
create_log_entry(void)
{
	lent_t	*lent;

	lent = (lent_t *)ecm_malloc(sizeof(lent_t));

	return lent;
}

static ECMBOOL
check_lent_sanity(lent_t *lent)
{
	media_t	*media = get_media(lent->mid);

	if (lent->playback_rate > 0 && lent->startstamp > media->length) {
		if (!suppress_display_error)
			ERR("Invalid startstamp: %u(media length: %u", lent->startstamp, media->length);
		return ECM_FALSE;
	}
	return ECM_TRUE;
}

static ECMBOOL
parse_log_file(const char *file)
{
	FILE	*fp;
	char	buf[BUFMAX];
	ecm_uint32	line = 1;
	lent_t	*lent;

	fp = ecm_fopen(file, "r");
	if (fp == NULL) {
		ERR("%s: cannot open");
		return ECM_FALSE;
	}

	lent = create_log_entry();

	while ((ecm_fgets(buf, BUFMAX, fp))) {
		if (!lparser_op->parse(buf, lent)) {
			if (mod_has_error) {
				if (!suppress_display_error) {
					ERR("parse log error in module: %s", mod_errmsg);
					ERR("%s: %u: has invalid log line", file, line);
				}
				if (stop_on_error)
					return ECM_FALSE;

				n_error_logs++;
				mod_has_error = ECM_FALSE;
			}
		}
		else {
			n_logs++;

			if (check_lent_sanity(lent)) {
				update_session(lent);
				update_request(lent);
			}
		}
		line++;
	}

	ecm_fclose(fp);
	return ECM_TRUE;
}

ECMBOOL
parse_logs(ecm_strlist_t files)
{
	char	*file;

	for (file = ecm_strlist_first(files);
	     file != NULL;
	     file = ecm_strlist_next(files))
		if (!parse_log_file(file))
			return ECM_FALSE;

	return ECM_TRUE;
}
